<script lang="tsx">
import { defineComponent, ref, reactive, onMounted, watch } from 'vue';
import { ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElRadioGroup, ElRadio, ElButton, ElMessage, ElUpload, ElRow, ElCol, ElCheckbox, ElDialog } from 'element-plus';
import { useRoute } from 'vue-router';
import { Plus, Info, FileText, CircleX } from '@vben/icons';
import { VbenIcon } from '@vben-core/shadcn-ui';
import { getGroupListApi, createUserRegistrationInfoApi, updateRegistrationInfoApi, getTeamInfoAndMembersListApi, getTrackListApi, queryMatchAgreementApi, RegistrationStatus, type Group, type EduRegWorksVO, type TeamFullInfo, type Track, type EduMatchAgreementVO } from '#/api/competition/registration-info';
import { obsUpload } from '#/utils/obs';

// 提交报名表单数据类型（继承API接口类型）
interface SubmissionFormData extends Omit<EduRegWorksVO, 'id' | 'createTime' | 'registrationReviewPeople' | 'registrationReviewTime' | 'registrationReviewOpinion' | 'worksReviewPeople' | 'worksReviewTime' | 'worksReviewOpinion'> {
  // 额外的表单字段
  copyrightFiles: any[]; // 著作权文件（用于上传）
  patentFiles: any[]; // 专利文件（用于上传）
  documentFiles: any[]; // 证明材料文件（用于上传）
}

export default defineComponent({
  name: 'SubmissionForm',
  props: {
    editData: {
      type: Object as () => EduRegWorksVO | null,
      default: null
    },
    onSubmitSuccess: {
      type: Function as unknown as () => () => void,
      default: () => () => { }
    }
  },
  emits: ['submit-success'],
  setup(props, { emit }) {
    // 获取路由实例
    const route = useRoute();

    // 表单数据
    const formData = reactive<SubmissionFormData>({
      // 必填字段
      compId: route.query.matchId as string,
      groupId: '',
      trackId: '',
      teamId: '',
      worksName: '',
      worksIntro: '',

      // 可选字段
      worksCopyright: '',
      worksPatent: '',
      accessChannel: '',
      videoAssetId: '',
      listedDocName: '',
      worksIntroduceFile: '',
      registrationStatus: 0,
      worksStatus: 0,
      dgEnterpriseCertificate: '',
      receivablesAccount: '',
      accountName: '',
      bankDeposit: '',
      companyAuthCertificate: '',
      worksLastTime: '',
      bonusPoint: false,
      groupName: '',
      trackName: '',
      teamName: '',
      compName: '',
      organizationName: '',
      trackMonth: '',
      idList: [],

      // 表单专用字段
      copyrightFiles: [],
      patentFiles: [],
      documentFiles: [] // 证明材料文件
    });

    // 表单验证规则
    const formRules = {
      groupId: [
        { required: true, message: '请选择参赛组别', trigger: 'change' }
      ],
      trackId: [
        { required: true, message: '请选择赛道', trigger: 'change' }
      ],
      teamId: [
        { required: true, message: '请选择团队', trigger: 'change' }
      ],
      worksName: [
        { required: true, message: '请输入作品名称', trigger: 'blur' },
        { max: 50, message: '作品名称不能超过50个字符', trigger: 'blur' }
      ],
      worksIntro: [
        { required: true, message: '请输入作品简介', trigger: 'blur' },
        { max: 500, message: '作品简介不能超过500个字符', trigger: 'blur' }
      ],
      receivablesAccount: [
        { required: true, message: '请输入收款账号', trigger: 'blur' }
      ],
      accountName: [
        { required: true, message: '请输入账号名', trigger: 'blur' }
      ],
      bankDeposit: [
        { required: true, message: '请输入开户行', trigger: 'blur' }
      ],
      accessChannel: [
        { required: true, message: '请选择了解渠道', trigger: 'change' }
      ]
    };

    // 组别选项数据（从API获取）
    const groupOptions = ref<Group[]>([]);
    const groupLoading = ref(false);

    // 赛道选项数据（从API获取）
    const trackOptions = ref<Track[]>([]);
    const trackLoading = ref(false);

    // 团队选项数据（从API获取）
    const teamOptions = ref<TeamFullInfo[]>([]);
    const teamLoading = ref(false);

    // 了解渠道选项
    const accessChannelOptions = [
      { label: '联盟官网', value: '联盟官网' },
      { label: '联盟公众号', value: '联盟公众号' },
      { label: '产教融合社区', value: '产教融合社区' },
      { label: '定向邀约', value: '定向邀约' },
      { label: '其他', value: '其他' }
    ];



    // 表单引用
    const formRef = ref();

    // 上传组件引用
    const copyrightUploadRef = ref();
    const patentUploadRef = ref();
    const documentUploadRef = ref();

    // 协议勾选状态
    const agreedToTerms = ref(false);

    // 协议相关状态
    const agreementVisible = ref(false);
    const agreementData = ref<EduMatchAgreementVO | null>(null);

    // 软件著作权选择状态
    const copyrightStatus = ref<'has' | 'none'>('none');

    // 专利信息选择状态
    const patentStatus = ref<'has' | 'none'>('none');

    // 监听状态变化，同步到formData
    watch(copyrightStatus, (newValue) => {
      if (newValue === 'none') {
        formData.worksCopyright = '';
        formData.copyrightFiles = [];
      }
    });

    watch(patentStatus, (newValue) => {
      if (newValue === 'none') {
        formData.worksPatent = '';
        formData.patentFiles = [];
      }
    });

    // 监听formData变化，同步到状态
    watch(() => formData.worksCopyright, (newValue) => {
      copyrightStatus.value = newValue ? 'has' : 'none';
    });

    watch(() => formData.worksPatent, (newValue) => {
      patentStatus.value = newValue ? 'has' : 'none';
    });

    // 监听团队选择变化，自动填充相关信息
    watch(() => formData.teamId, (newTeamId) => {
      if (newTeamId) {
        const selectedTeam = teamOptions.value.find(team => team.id === newTeamId);
        if (selectedTeam) {
          // 自动填充团队相关信息
          formData.teamName = selectedTeam.name;
          formData.organizationName = selectedTeam.organName;
          formData.groupId = selectedTeam.groupId; // 自动选择组别
        }
      }
    });

    // 监听组别选择变化，重新获取对应的赛道数据
    watch(() => formData.groupId, (newGroupId) => {
      if (newGroupId) {
        // 清空当前赛道选择
        formData.trackId = '';
        // 根据新组别获取赛道数据
        fetchTrackOptions(newGroupId);
      }
    });

    // 监听赛道选择变化，自动填充赛道名称
    watch(() => formData.trackId, (newTrackId) => {
      if (newTrackId) {
        const selectedTrack = trackOptions.value.find(track => track.id === newTrackId);
        if (selectedTrack) {
          formData.trackName = selectedTrack.name;
        }
      }
    });

    // 文件上传前处理
    const beforeUpload = (file: File) => {
      const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type);
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isValidType) {
        ElMessage.error('只能上传 pdf、jpg、jpeg、png 格式的文件!');
        return false;
      }
      if (!isLt10M) {
        ElMessage.error('上传文件大小不能超过 10MB!');
        return false;
      }
      return true;
    };

    // 著作权文件上传到OBS
    const uploadCopyrightToObs = async (file: File): Promise<void> => {
      return new Promise((resolve, reject) => {
        obsUpload({
          Key: file.name,
          SourceFile: file,
          ContentType: file.type
        }, (err: any, _result: any, uploadedKey: string) => {
          if (err) {
            reject(err);
            return;
          }
          // 保存文件key给后端
          formData.worksCopyright = uploadedKey;
          formData.copyrightFiles = [{ name: file.name, key: uploadedKey, uid: Date.now() }];
          ElMessage.success('著作权文件上传成功');
          resolve();
        });
      });
    };

    // 专利文件上传到OBS
    const uploadPatentToObs = async (file: File): Promise<void> => {
      return new Promise((resolve, reject) => {
        obsUpload({
          Key: file.name,
          SourceFile: file,
          ContentType: file.type
        }, (err: any, _result: any, uploadedKey: string) => {
          if (err) {
            reject(err);
            return;
          }
          // 保存文件key给后端
          formData.worksPatent = uploadedKey;
          formData.patentFiles = [{ name: file.name, key: uploadedKey, uid: Date.now() }];
          ElMessage.success('专利文件上传成功');
          resolve();
        });
      });
    };

    // 著作权文件上传成功处理
    const handleCopyrightUploadSuccess = async (file: any, _fileList: any[]) => {
      try {
        // 只处理新上传的文件
        if (file.status === 'ready') {
          await uploadCopyrightToObs(file.raw || file);
        }
      } catch (error) {
        console.error('著作权文件上传失败:', error);
      }
    };

    // 专利文件上传成功处理
    const handlePatentUploadSuccess = async (file: any, _fileList: any[]) => {
      try {
        // 只处理新上传的文件
        if (file.status === 'ready') {
          await uploadPatentToObs(file.raw || file);
        }
      } catch (error) {
        console.error('专利文件上传失败:', error);
      }
    };

    // 著作权文件删除处理
    const handleCopyrightRemove = (_file: any) => {
      formData.copyrightFiles = [];
      formData.worksCopyright = ''; // 清空URL
    };

    // 专利文件删除处理
    const handlePatentRemove = (_file: any) => {
      formData.patentFiles = [];
      formData.worksPatent = ''; // 清空URL
    };

    // 证明材料文件上传到OBS
    const uploadDocumentToObs = async (file: File): Promise<string> => {
      return new Promise((resolve, reject) => {
        obsUpload({
          Key: file.name,
          SourceFile: file,
          ContentType: file.type
        }, (err: any, _result: any, uploadedKey: string) => {
          if (err) {
            reject(err);
            return;
          }
          resolve(uploadedKey);
        });
      });
    };

    // 证明材料文件上传成功处理
    const handleDocumentUploadSuccess = async (file: any, _fileList: any[]) => {
      try {
        // 只处理新上传的文件
        if (file.status === 'ready') {
          const realFile = file.raw || file;
          const uploadedKey = await uploadDocumentToObs(realFile);
          // 添加文件到列表，保存文件key和相关信息
          const newFile = {
            name: realFile.name,
            key: uploadedKey,
            uid: file.uid || Date.now()
          };
          formData.documentFiles.push(newFile);
          ElMessage.success('证明材料上传成功');
        }
      } catch (error) {
        console.error('证明材料上传失败:', error);
      }
    };

    // 证明材料文件删除处理
    const handleDocumentRemove = (file: any) => {
      const index = formData.documentFiles.findIndex(item => item.uid === file.uid);
      if (index > -1) {
        formData.documentFiles.splice(index, 1);
      }
    };

    // 著作权文件选择处理
    const handleCopyrightSelectFile = () => {
      // 检查是否已经有文件
      if (formData.copyrightFiles.length > 0) {
        ElMessage.error('请先删除已上传的文件');
        return;
      }

      // 手动触发文件选择器
      if (copyrightUploadRef.value) {
        const inputElement = copyrightUploadRef.value.$el.querySelector('input[type="file"]');
        if (inputElement) {
          inputElement.click();
        }
      }
    };

    // 专利文件选择处理
    const handlePatentSelectFile = () => {
      // 检查是否已经有文件
      if (formData.patentFiles.length > 0) {
        ElMessage.error('请先删除已上传的文件');
        return;
      }

      // 手动触发文件选择器
      if (patentUploadRef.value) {
        const inputElement = patentUploadRef.value.$el.querySelector('input[type="file"]');
        if (inputElement) {
          inputElement.click();
        }
      }
    };

    // 证明材料文件选择处理
    const handleDocumentSelectFile = () => {
      // 手动触发文件选择器
      if (documentUploadRef.value) {
        const inputElement = documentUploadRef.value.$el.querySelector('input[type="file"]');
        if (inputElement) {
          inputElement.click();
        }
      }
    };

    // 获取大赛协议
    const fetchMatchAgreement = async () => {
      try {
        const matchId = route.query.matchId as string;
        if (!matchId) {
          console.error('缺少大赛ID参数');
          return;
        }

        const data = await queryMatchAgreementApi({ matchId });
        agreementData.value = data;
      } catch (error) {
        console.error('获取大赛协议失败:', error);
      }
    };

    // 显示协议弹窗
    const showAgreement = () => {
      agreementVisible.value = true;
    };

    // 提交表单（直接提交）
    const submitForm = async () => {
      try {
        await formRef.value?.validate();

        // 检查协议勾选
        if (!agreedToTerms.value) {
          ElMessage.error('请先阅读并同意比赛协议');
          return;
        }

        await submitData(RegistrationStatus.PENDING); // 直接提交，状态为待审核
      } catch (error: any) {
        console.error('提交报名失败:', error);
      }
    };

    // 通用提交数据函数
    const submitData = async (status: number) => {
      // 准备提交数据，移除表单专用字段
      const submitPayload: EduRegWorksVO = {
        ...formData,
        registrationStatus: status, // 设置状态：DRAFT-草稿，PENDING-待审核
        // 移除表单专用字段
        copyrightFiles: undefined,
        patentFiles: undefined,
        documentFiles: undefined
      } as any;

      // 删除不需要的字段
      delete (submitPayload as any).copyrightFiles;
      delete (submitPayload as any).patentFiles;
      delete (submitPayload as any).documentFiles;

      console.log('提交表单数据:', submitPayload);

      // 根据是否有editData判断是创建还是更新
      const isEdit = !!props.editData;

      if (isEdit) {
        // 更新操作：调用更新接口
        await updateRegistrationInfoApi(submitPayload);
      } else {
        // 创建操作：调用创建接口
        await createUserRegistrationInfoApi(submitPayload);
      }

      // API调用成功，显示成功提示
      const message = isEdit
        ? (status === RegistrationStatus.DRAFT ? '草稿更新成功！' : '报名信息更新成功！')
        : (status === RegistrationStatus.DRAFT ? '草稿保存成功！' : '提交报名成功！');
      ElMessage.success(message);

      // 如果是正式提交（非草稿），则触发成功回调
      if (status !== RegistrationStatus.DRAFT) {
        handleSubmitSuccess();
      }
    };

    // 保存草稿
    const saveDraft = async () => {
      try {
        // 保存草稿时也需要进行表单校验
        await formRef.value?.validate();

        // 检查协议勾选
        if (!agreedToTerms.value) {
          ElMessage.error('请先阅读并同意比赛协议');
          return;
        }

        await submitData(RegistrationStatus.DRAFT); // 保存草稿，状态为草稿
      } catch (error: any) {
        console.error('保存草稿失败:', error);
      }
    };

    // 获取组别选项数据
    const fetchGroupOptions = async () => {
      try {
        groupLoading.value = true;
        // 从路由query参数中获取matchId作为compId
        const matchId = route.query.matchId as string;

        if (!matchId) {
          ElMessage.error('缺少大赛ID参数');
          return;
        }

        // 项目axios已封装错误处理，直接获取数据
        const response = await getGroupListApi({
          compId: matchId,
          curPage: 1,
          pageSize: 100
        });

        groupOptions.value = response.data || [];
      } catch (error) {
        console.error('获取组别数据失败:', error);
        groupOptions.value = [];
      } finally {
        groupLoading.value = false;
      }
    };

    // 获取团队选项数据
    const fetchTeamOptions = async () => {
      try {
        teamLoading.value = true;
        // 从路由query参数中获取matchId作为compId
        const matchId = route.query.matchId as string;

        if (!matchId) {
          ElMessage.error('缺少大赛ID参数');
          return;
        }

        // 项目axios已封装错误处理，直接获取数据
        const response = await getTeamInfoAndMembersListApi({
          compId: matchId,
          curPage: 1,
          pageSize: 100
        });

        teamOptions.value = response.data || [];
      } catch (error) {
        console.error('获取团队数据失败:', error);
        teamOptions.value = [];
      } finally {
        teamLoading.value = false;
      }
    };

    // 获取赛道选项数据
    const fetchTrackOptions = async (groupId: string) => {
      try {
        trackLoading.value = true;
        // 从路由query参数中获取matchId作为compId
        const matchId = route.query.matchId as string;

        if (!matchId) {
          ElMessage.error('缺少大赛ID参数');
          return;
        }

        if (!groupId) {
          // 如果没有组别ID，清空赛道选项
          trackOptions.value = [];
          return;
        }

        // 项目axios已封装错误处理，直接获取数据
        const response = await getTrackListApi({
          compId: matchId,
          groupId: groupId, // 必须传递组别ID
          curPage: 1,
          releaseStatus: '1' // 只获取已发布的赛道
        });

        trackOptions.value = response.data || [];
      } catch (error) {
        console.error('获取赛道数据失败:', error);
        trackOptions.value = [];
      } finally {
        trackLoading.value = false;
      }
    };

    // 渲染表单内容
    const renderForm = () => (
      <ElForm
        ref={formRef}
        model={formData}
        rules={formRules}
        label-width="120px"
      >
        <ElRow>
          <ElCol span={12}>
            <ElFormItem label="选择团队" prop="teamId">
              <ElSelect
                v-model={formData.teamId}
                placeholder="请选择"
                loading={teamLoading.value}
                style={{ width: '100%' }}
              >
                {teamOptions.value.map(option => (
                  <ElOption
                    key={option.id}
                    label={option.name}
                    value={option.id}
                  />
                ))}
              </ElSelect>
            </ElFormItem>
            <ElFormItem label="所属赛题" prop="trackId">
              <ElSelect
                v-model={formData.trackId}
                placeholder="请选择"
                loading={trackLoading.value}
                style={{ width: '100%' }}
              >
                {trackOptions.value.map(option => (
                  <ElOption
                    key={option.id}
                    label={option.name}
                    value={option.id}
                  />
                ))}
              </ElSelect>
            </ElFormItem >
          </ElCol>
          <ElCol span={12}>
            {/* 参赛组别 */}
            <ElFormItem label="参赛组别" prop="groupId">
              <ElSelect
                v-model={formData.groupId}
                placeholder="请选择"
                loading={groupLoading.value}
                style={{ width: '100%' }}
              >
                {groupOptions.value.map(option => (
                  <ElOption
                    key={option.id}
                    label={option.name}
                    value={option.id}
                  />
                ))}
              </ElSelect>
            </ElFormItem >
            {/* 作品名称 */}
            <ElFormItem label="作品名称" prop="worksName">
              <ElInput
                v-model={formData.worksName}
                placeholder="请输入"
                maxlength={50}
                show-word-limit
              />
            </ElFormItem >
          </ElCol>
        </ElRow >
        {/* 作品简介 */}
        <ElFormItem label="作品简介" prop="worksIntro">
          <ElInput
            v-model={formData.worksIntro}
            type="textarea"
            placeholder="请简要介绍作品功能、技术特点等"
            rows={4}
            maxlength={500}
            show-word-limit
          />
        </ElFormItem >
        <ElRow gutter={24}>
          <ElCol span={12}>
            {/* 软件著作权 */}
            <ElFormItem label="软件著作权">
              <ElRadioGroup v-model={copyrightStatus.value}>
                <ElRadio value="has">有著作权</ElRadio>
                <ElRadio value="none">无著作权</ElRadio>
              </ElRadioGroup>
              {/* 条件显示著作权文件上传 */}
              {copyrightStatus.value === 'has' && (
                <div class="mt-3 w-full">
                  {/* 隐藏的文件上传组件 */}
                  <ElUpload
                    ref={copyrightUploadRef}
                    action="#"
                    limit={1}
                    auto-upload={false}
                    accept=".pdf,.jpg,.jpeg,.png"
                    before-upload={beforeUpload}
                    on-change={handleCopyrightUploadSuccess}
                    show-file-list={false}
                    style={{ display: 'none' }}
                  />

                  {/* 自定义上传按钮 */}
                  <div class="flex items-center">
                    <ElButton icon={Plus} onClick={handleCopyrightSelectFile}>
                      选择文件
                    </ElButton>
                    <div class="text-xs text-gray-500 ml-2">
                      支持格式：pdf、jpg、jpeg、png，文件不超过10MB
                    </div>
                  </div>

                  {/* 自定义文件列表显示 */}
                  {formData.copyrightFiles.length > 0 && (
                    <div class="mt-3 w-full">
                      {formData.copyrightFiles.map((file: any, index: number) => (
                        <div key={index} class="px-3 py-2 bg-[#F2F7FD] rounded-md w-[95%]">
                          <div class="flex items-center justify-between">
                            <div class="flex items-center">
                              <VbenIcon icon={FileText} class="text-blue-500 mr-2 w-4 h-4" />
                              <span class="text-sm text-gray-700">{file.name}</span>
                            </div>
                            <ElButton size="small" icon={CircleX} link onClick={() => handleCopyrightRemove(file)} />
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </ElFormItem>
          </ElCol>
          <ElCol span={12}>
            {/* 专利信息 */}
            <ElFormItem label="专利信息">
              <ElRadioGroup v-model={patentStatus.value}>
                <ElRadio value="has">有专利</ElRadio>
                <ElRadio value="none">无专利</ElRadio>
              </ElRadioGroup>
              {/* 条件显示专利文件上传 */}
              {patentStatus.value === 'has' && (
                <div class="mt-3 w-full">
                  {/* 隐藏的文件上传组件 */}
                  <ElUpload
                    ref={patentUploadRef}
                    action="#"
                    limit={1}
                    auto-upload={false}
                    accept=".pdf,.jpg,.jpeg,.png"
                    before-upload={beforeUpload}
                    on-change={handlePatentUploadSuccess}
                    show-file-list={false}
                    style={{ display: 'none' }}
                  />

                  {/* 自定义上传按钮 */}
                  <div class="flex items-center">
                    <ElButton icon={Plus} onClick={handlePatentSelectFile}>
                      选择文件
                    </ElButton>
                    <div class="text-xs text-gray-500 ml-2">
                      支持格式：pdf、jpg、jpeg、png，文件不超过10MB
                    </div>
                  </div>

                  {/* 自定义文件列表显示 */}
                  {formData.patentFiles.length > 0 && (
                    <div class="mt-3 w-full">
                      {formData.patentFiles.map((file: any, index: number) => (
                        <div key={index} class="px-3 py-2 bg-[#F2F7FD] rounded-md w-[95%]">
                          <div class="flex items-center justify-between">
                            <div class="flex items-center">
                              <VbenIcon icon={FileText} class="text-blue-500 mr-2 w-4 h-4" />
                              <span class="text-sm text-gray-700">{file.name}</span>
                            </div>
                            <ElButton size="small" icon={CircleX} link onClick={() => handlePatentRemove(file)} />
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </ElFormItem>
          </ElCol>
        </ElRow>
        <ElRow gutter={24}>
          <ElCol span={12}>
            <ElFormItem label="了解渠道" prop="accessChannel">
              <ElSelect
                v-model={formData.accessChannel}
                placeholder="请选择"
                style={{ width: '100%' }}
              >
                {accessChannelOptions.map(option => (
                  <ElOption
                    key={option.value}
                    label={option.label}
                    value={option.value}
                  />
                ))}
              </ElSelect>
            </ElFormItem>
          </ElCol>
        </ElRow>
        {/* 说明文字 */}
        <div class="bg-blue-50 border border-blue-200 rounded-md py-[10px] my-6 flex">
          <VbenIcon icon={Info} class="w-[20px] h-[20px] ml-[17px] mr-[8px] text-blue-500" />
          <div class="text-[14px] leading-[22px]">
            <p>1、填写团队所属单位账户信息(用于获奖单位奖金发放);2、账号一经填写并提交，原则上不得修改。如后续修改，必须提供原单位盖章授权证明;</p>
            <p>3、如填写为个人账号，须提供单位盖章授权证明。</p>
          </div>
        </div>

        {/* 财务信息 */}
        <ElRow gutter={24}>
          <ElCol span={12}>
            <ElFormItem label="收款账号" prop="receivablesAccount">
              <ElInput
                v-model={formData.receivablesAccount}
                placeholder="请输入"
              />
            </ElFormItem>
          </ElCol>
          <ElCol span={12}>
            <ElFormItem label="账户名" prop="accountName">
              <ElInput
                v-model={formData.accountName}
                placeholder="请输入"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
        <ElRow gutter={24}>
          <ElCol span={12}>
            <ElFormItem label="开户行" prop="bankDeposit">
              <ElInput
                v-model={formData.bankDeposit}
                placeholder="请输入"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElRow gutter={24}>
          <ElCol span={12}>
            {/* 证明材料 */}
            <ElFormItem label="证明材料">
              {/* 隐藏的文件上传组件 */}
              <ElUpload
                ref={documentUploadRef}
                action="#"
                multiple
                auto-upload={false}
                accept=".pdf,.jpg,.jpeg,.png"
                before-upload={beforeUpload}
                on-change={handleDocumentUploadSuccess}
                show-file-list={false}
                style={{ display: 'none' }}
              />

              {/* 自定义上传按钮 */}
              <div class="flex items-center">
                <ElButton icon={Plus} onClick={handleDocumentSelectFile}>
                  选择文件
                </ElButton>
                <div class="text-xs text-gray-500 ml-2">
                  支持pdf、jpg、jpeg、png格式文件，大小不超过10M。
                </div>
              </div>

              {/* 自定义文件列表显示 */}
              {formData.documentFiles.length > 0 && (
                <div class="mt-3 w-full">
                  {formData.documentFiles.map((file: any, index: number) => (
                    <div key={index} class="px-3 py-2 bg-[#F2F7FD] rounded-md w-[95%] mb-2">
                      <div class="flex items-center justify-between">
                        <div class="flex items-center">
                          <VbenIcon icon={FileText} class="text-blue-500 mr-2 w-4 h-4" />
                          <span class="text-sm text-gray-700">{file.name}</span>
                        </div>
                        <ElButton size="small" icon={CircleX} link onClick={() => handleDocumentRemove(file)} />
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </ElFormItem>
          </ElCol>
        </ElRow>
      </ElForm >
    );

    // 渲染底部按钮
    const renderFooter = () => (
      <div class="flex justify-end items-center pt-5 border-t border-gray-200">
        <div class="flex items-center gap-4">
          <div class="flex items-center text-sm text-gray-600">
            <ElCheckbox v-model={agreedToTerms.value} class="mr-2" />
            <span class="mr-1">我已阅读并全部同意</span>
            <a
              href="#"
              class="text-blue-600 no-underline mx-1 hover:underline"
              onClick={(e: Event) => {
                e.preventDefault();
                showAgreement();
              }}
            >
              {agreementData.value?.agreementName || '比赛协议'}
            </a>
          </div>
          <ElButton onClick={saveDraft} class="min-w-[100px]">
            保存草稿
          </ElButton>
          <ElButton type="primary" onClick={submitForm} class="min-w-[100px]">
            提交报名
          </ElButton>
        </div>
      </div>
    );

    // 监听编辑数据变化，回填表单
    watch(() => props.editData, (newData) => {
      if (newData) {
        console.log('回填表单数据:', newData);
        // 回填基本信息
        Object.assign(formData, {
          ...newData,
          // 确保表单专用字段存在
          copyrightFiles: formData.copyrightFiles,
          patentFiles: formData.patentFiles,
          documentFiles: formData.documentFiles
        });
      }
    }, { immediate: true });

    // 监听提交成功后的回调
    const handleSubmitSuccess = () => {
      emit('submit-success');
      props.onSubmitSuccess?.();
    };

    // 组件挂载时获取数据
    onMounted(() => {
      fetchGroupOptions();
      fetchTeamOptions();
      fetchMatchAgreement();
    });

    return () => (
      <div class="bg-white rounded-lg p-6 w-full">
        <div class="mb-6">
          {renderForm()}
        </div>

        {renderFooter()}

        {/* 协议弹窗 */}
        <ElDialog
          v-model={agreementVisible.value}
          title={agreementData.value?.agreementName || '比赛协议'}
          width="800px"
          destroy-on-close
        >
          <div
            class="max-h-[500px] overflow-y-auto p-4 text-sm leading-6"
            v-html={agreementData.value?.agreementContent || ''}
          />
        </ElDialog>
      </div>
    );
  }
});
</script>

<style scoped>
/* Element Plus 表单项样式调整 */
.max-w-2xl :deep(.el-form-item) {
  margin-bottom: 20px;
}

.max-w-2xl :deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
}
</style>
